package com.turing.usdtpay.mvp.presenter;

import com.turing.usdtpay.entity.LoginData;
import com.turing.usdtpay.http.ApiService;
import com.turing.usdtpay.http.ApiUrl;
import com.turing.usdtpay.http.callback.ApiCallback;
import com.turing.usdtpay.http.entity.ResponseDate;
import com.turing.usdtpay.manager.UserManager;
import com.turing.usdtpay.mvp.contract.LoginContract;
import com.turing.usdtpay.utils.LogUtils;
import com.turing.usdtpay.utils.SPHelper;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

/**
 * @作者：JAY
 * @创建时间：2019/10/23 11:04
 * @描述：
 **/
public class LoginPresenter implements LoginContract.Present {
    private LoginContract.View mView;

    public LoginPresenter(LoginContract.View view) {
        this.mView = view;
    }

    @Override
    public void login(final String account, final String pwd) {
        HashMap<String,String> map = new HashMap<>();
        map.put("act",account);
        map.put("pwd",pwd);
        LogUtils.d("login");
        ApiService.getInstance().postRequest(ApiUrl.API_DOLOGIN, map, new ApiCallback() {
            @Override
            public void onSuccess(int code, ResponseDate date) {
                if (date.getRet() == 1){
                    try {
                        JSONObject object = new JSONObject(date.getDate());
                        String trader = object.optString("trader");
                        String verfiy = object.optString("verfiy");
                        LoginData data = new LoginData();
                        data.setAccount(account);
                        data.setPwd(pwd);
                        data.setTrader(trader);
                        data.setVerify(verfiy);
                        LogUtils.d("data -->"+date.toString());
                        UserManager.getInstance().saveLoginInfo(data);
                        UserManager.getInstance().saveAccount(account,pwd);
                        UserManager.getInstance().saveInfo(account,trader,verfiy);
                        mView.loginSuccess();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }else {
                    mView.loginFail(date.getMsg());
                }
            }

            @Override
            public void onFailure(Throwable exception) {
                mView.loginFail(exception.getMessage());
            }

            @Override
            public void onFailureFilter(Throwable exception) {
                mView.loginFail(exception.getMessage());
            }
        });

    }
}
